package lion.framework.core.web.anno;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.apache.commons.io.FilenameUtils;

import lion.dev.lang.MapJ;
import lion.framework.core.anno.AnnoProcessor;
import lion.framework.core.anno.AnnotationProcessorManager;
import lion.framework.core.anno.IAnnotationProcessor;
import lion.framework.core.web.path.PathNode;
import lion.framework.core.web.path.PathNodeMapping;
import lion.framework.core.web.path.PathVar;

/**
 * 路径映射处理类，处理@Path注解
 *
 * <pre>
 * time   2013 2013-4-24 上午11:29:43
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@AnnoProcessor(Path.class)
public class PathMappingProcessor implements IAnnotationProcessor {

	public static final String PATH_NODE = "pathnode";

	@Override
	public void processe(MapJ ctx, Annotation anno) {

		Method method = ctx.getE(AnnotationProcessorManager.ANNO_CONTEXT_TARGET);

		Path path = (Path) anno;

		Class<?> clazz = ctx.getE(AnnotationProcessorManager.ANNO_CONTEXT_CLASS);

		Namespace ns = clazz.getAnnotation(Namespace.class);
		String pkg = "";
		if (ns != null) {
			pkg = ns.value();
		}
		if (!pkg.endsWith("/")) {
			pkg += "/";
		}

		for (String p : path.value()) {

			String pathm = FilenameUtils.separatorsToUnix(pkg + p);
			pathm = PathVar.replacePathVars(pathm);

			PathNode node = PathNodeMapping.add(pathm);
			node.setMethodType(path.method().name());
			node.setMethod(method);
			node.setSingleton(path.singleton());
			node.setAsync(path.async());
			ViewProcessor processor = new ViewProcessor();
			ctx.put(PATH_NODE, node);
			processor.processe(ctx, method.getAnnotation(Result.class));
			ctx.remove(PATH_NODE);
		}
	}
}
